import { getDailyMeals, addMealRecord, updateMealRecord, deleteMealRecord } from '@/api/meals'

export default {
  namespaced: true,
  state: {
    dailyMeals: [],
    loading: false
  },
  mutations: {
    SET_DAILY_MEALS(state, meals) {
      state.dailyMeals = meals
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    }
  },
  actions: {
    async getDailyMeals({ commit, rootGetters }, date) {
      try {
        commit('SET_LOADING', true)
        const userId = rootGetters['user/userId']
        if (!userId) {
          throw new Error('用户未登录')
        }
        const res = await getDailyMeals({ date, userId })
        if (res.code === 200) {
          commit('SET_DAILY_MEALS', res.data || [])
          return res.data
        }
        throw new Error(res.message || '获取膳食记录失败')
      } catch (error) {
        console.error('获取每日膳食记录失败:', error)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async addMealRecord({ dispatch }, data) {
      try {
        const res = await addMealRecord(data)
        await dispatch('getDailyMeals', new Date(data.date))
        return res
      } catch (error) {
        console.error('添加膳食记录失败:', error)
        throw error
      }
    },
    async updateMealRecord({ dispatch }, { id, data }) {
      try {
        const res = await updateMealRecord(id, data)
        await dispatch('getDailyMeals', new Date(data.date))
        return res
      } catch (error) {
        console.error('更新膳食记录失败:', error)
        throw error
      }
    },
    async deleteMealRecord({ dispatch }, { id, date }) {
      try {
        const res = await deleteMealRecord(id)
        await dispatch('getDailyMeals', new Date(date))
        return res
      } catch (error) {
        console.error('删除膳食记录失败:', error)
        throw error
      }
    }
  }
} 